package com.meiyu.live.net;

import android.util.Log;

import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.meiyu.live.BaseApplication;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class LiveRequest<T> extends Request<T> {

    /**
     * Charset for request.
     */
    private static final String PROTOCOL_CHARSET = "UTF-8";

    /**
     * Content type for request.
     */

    private final Listener<T> mListener;

    private final String mRequestBody;

    private Class<T> mJavaClass;

    private Map<String, String> headers = new HashMap<String, String>();

    public LiveRequest(int method, String url, Class<T> cls, String requestBody,
                       Listener<T> listener, ErrorListener errorListener) {
        super(method,
                url,
                errorListener);
        mJavaClass = cls;
        mListener = listener;
        mRequestBody = requestBody;
    }

    @Override
    protected void deliverResponse(T response) {

        mListener.onResponse(response);
    }

//    @Override
//    public Map<String, String> getHeaders() throws AuthFailureError {
//        return headers;
//    }


    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            Log.i("net-response:" + getUrl(), jsonString);

            String hash;
            JsonParser parser = new JsonParser();
            JsonElement jsonEl = parser.parse(jsonString);
            JsonObject jsonObj = jsonEl.getAsJsonObject();
            T parsedGSON = null;
            if (200 == jsonObj.get("code").getAsInt()) {
                hash = jsonObj.get("hash").toString();
                JsonElement hashEl = parser.parse(hash);
                if (hashEl.isJsonArray()) {
                    parsedGSON = BaseApplication.mGson.fromJson(jsonString,
                            mJavaClass);
                } else {
                    jsonObj = hashEl.getAsJsonObject();
                    if (jsonObj.has("StatusCode") && jsonObj.get("StatusCode").getAsInt() == 0) {
                        BaseApplication.getApp().logout(true);
                    } else {
                        parsedGSON = BaseApplication.mGson.fromJson(hash,
                                mJavaClass);
                    }
                }
            } else {
                return Response.error(new NetworkError());
            }

            return Response.success(parsedGSON,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    public String getBodyContentType() {
        return "application/json;charset=utf-8";
    }

    @Override
    public byte[] getBody() {
//        try {
//            return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
//        } catch (UnsupportedEncodingException uee) {
//            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
//                    mRequestBody,
//                    PROTOCOL_CHARSET);
//            Log.e("getBody", "UnsupportedEncodingException: ");
//            return null;
//        }
        return mRequestBody.getBytes();
    }

}
